<!--  -->
<template>
  <div class=''>
    <el-form ref="formInline" :inline="true" size="small" :model="formInline" class="demo-form-inline">
      <el-form-item label="角色名" prop="user">
        <el-input v-model="formInline.user" placeholder="角色名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="getRoleListFun"
          class="queryButton"
          icon="el-icon-search">查询</el-button>
        <el-button
          class="resetButton"
          @click="resetQuery('formInline')"
          icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-button
        type="primary"
        plain
        class="queryButton"
        @click="addRoleBtn"
        v-permissions="'role:add'"
        icon="el-icon-plus">新增</el-button>
    </el-form>
    <!-- 新增角色弹框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="isShowaddRole"
      @close="closeAddPop('roleForm')"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      width="25%">
      <el-form ref="roleForm" size="small" :model="roleFromAdd" :rules="addRoleRule" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleFromAdd.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="permission">
          <el-select v-model="roleFromAdd.permission" placeholder="请选择">
            <el-option
            v-for="(item,index) in permissionRole"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="roleFromAdd.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div style="width: 100%; text-align: center;">
        <el-button 
          type="primary"
          plain
          @click="submitRole"
          class="queryButton">保存</el-button>
        <el-button
          plain
          class="resetButton"
          @click="closeAddPop('roleForm')">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 详情角色弹框 -->
    <el-dialog
      title="角色详情"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="true"
      width="40%">
      <el-form ref="basicForm"
        :disabled="isDisable"
        :inline="false"
        :model="roleDetailObj"
        :rules="rulesDetail"
        size="small"
        class="demo-form-inline"
        label-position="left"
        label-width="220px">
        <div class="filter-container">
          <el-form-item label="角色名" prop="userNameGet">
            <el-input v-model="roleDetailObj.userNameGet"></el-input>
          </el-form-item>
          <el-form-item label="角色权限" prop="permission">
            <el-select v-model="roleDetailObj.permission" placeholder="请选择">
              <el-option
                v-for="(item,index) in permissionRole"
                :key="index"
                :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="userRemarkGet">
            <el-input v-model="roleDetailObj.userRemarkGet"></el-input>
          </el-form-item>
          <el-form-item label="部门权限">
            <el-tree
              :data="userList"
              show-checkbox
              :check-strictly="defaultRelev"
              :getCheckedNodes="false"
              :default-expand-all="false"
              node-key="id"
              ref="adminTree"
              highlight-current
              :default-checked-keys="defaultCheckRole"
              @check="roleNodeChange"
              :props="defaultProps">
            </el-tree>
          </el-form-item>

        </div>
      </el-form>
      <el-form class="buttons">
        <el-button
          type="primary"
          class="submitButton"
          @click="setConfigUserRole"
          v-permissions="'role:update'"
          v-if="isDisable">修改</el-button>
        <el-button
          type="primary"
          class="submitButton"
          @click="addConfigUserRole"
          v-if="!isDisable">保存</el-button>
        <el-button
          class="resetButton"
          @click="closeDia">关闭</el-button>
      </el-form>
    </el-dialog>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      :header-cell-style="{ background:'#f8f8f9',color:'#515a6e'}"
      size="mini"
      style="width: 100%; margin-top: 5px;">
      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名"
        width="90">
      </el-table-column>
      <el-table-column
        prop="rRemarks"
        label="备注"
        width="90">
      </el-table-column>
      <el-table-column
        label="角色权限"
        width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.permission === 0 ? '仅自己' : scope.row.permission === 1 ? '当前部门' : scope.row.permission === 2 ? '全公司' : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        width="200"
        :show-overflow-tooltip="true"
        label="创建时间">
        <template slot-scope="scope">
          <span>{{ timestampToDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-permissions="'role:detail'"
            @click="getRoleDetail(scope.row.id,scope.row.roleName,scope.row.rRemarks,scope.row.permission)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-permissions="'role:delete'"
            @click="deletRole(scope.row.id,scope.row.roleName)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      class="pagination_container"
      :total="paginationForOut.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="paginationForOut.page"
      :limit.sync="paginationForOut.pageSize"
      @pagination="getRoleListFun"
    />
  </div>
</template>

<script>
import { roleAdd, roleList,roleDetail,roleUpdate,roleDelete } from '@/request/role';
import storages from '@/until/localStorage';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
    data() {
    //这里存放数据
      return {
        roleDetailObj: {
          userNameGet: '',
          userRemarkGet: '',
          permission: ''
        },
        rulesDetail: {
          userNameGet: [
            { required: true, trigger: 'blur', message: '请输入您的名字' }
          ],
          permission: [
            { required: true, trigger: 'change', message: '请选择角色权限' }
          ],
          // userRemarkGet: [
          //   { required: true, trigger: 'blur', message: '请输入您的名字' }
          // ]
        },
        dialogVisible: false,
        isDisable: true,
        defaultRelev: true,
        userRoleIdGet: null,
        defaultCheckRole: [],
        setRoleIdArrFir: [],
        setRoleIdArrSen: [],
        userList: JSON.parse(storages.getItem('routerList')),
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        roleFromAdd: {
          roleName: '',
          permission: '',
          remarks: ''
        },
        addRoleRule: {
          roleName: [
            { required: true, trigger: 'blur', message: '请输入您的名字' }
          ],
          permission: [
            { required: true, trigger: 'change', message: '请选择角色权限' }
          ]
        },
        isShowaddRole: false,
        permissionRole: [
          {
            name: '仅自己',
            id: 0
          },
          {
            name: '当前部门',
            id: 1
          },
          {
            name: '全公司',
            id: 2
          }
        ],
        paginationForOut: {
          page: 1,
          pageSize: 10,
          total: 20
        },
        formInline: {
          user: ''
        },
        tableData: []
      };
    },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 删除角色
    deletRole(id,name){
      this.$confirm(`是否确认删除’${name}‘`, '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        roleDelete(id).then(res => {
          if (res.code === '200') {
            this.getRoleListFun()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        }).catch(err => {
          this.$message({
            message: '服务器忙~',
            type: 'warning'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 获取角色列表
    getRoleListFun(){
      const roleListObj = {
        endTime: '',
        kw: this.formInline.user,
        limit: this.paginationForOut.pageSize,
        page: this.paginationForOut.page,
        startTime: ''
      }
      roleList(roleListObj).then(res => {
        if(res.code === '200') {
          this.tableData = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.paginationForOut.size) < this.paginationForOut.page) {
            this.paginationForOut.page = Math.ceil(res.data.total / this.paginationForOut.size)
            this.getRoleListFun()
          } else {
            this.paginationForOut.total = res.data.total
          }
        } else {
          this.tableData = []
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // 新增角色
    addRoleBtn(){
      this.isShowaddRole = true
    },
    // 提交新角色
    submitRole(){
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          roleAdd(this.roleFromAdd).then(res => {
            if (res.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.closeAddPop('roleForm')
              this.getRoleListFun()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {
            this.$message({
              message: '服务器忙~',
              type: 'warning'
            })
          })
        }
      })
    },
    // 关闭新增弹框
    closeDia(){
      this.isShowaddRole = false
      this.dialogVisible = false
    },
    // 角色详情
    getRoleDetail (val, name, rRemarks, permission) {
      this.defaultRelev = true
      this.roleDetailObj.userNameGet = name
      this.roleDetailObj.userRoleIdGet = val
      this.roleDetailObj.permission = permission
      this.roleDetailObj.userRemarkGet = rRemarks
      const arrNull = []
      this.defaultCheckRole = []
      roleDetail({roleId:val}).then(res => {
        if (res.data.length >= 1) {
          for (const key of res.data) {
            arrNull.push(key.id)
            if (key.children) {
              for (const item of key.children) {
                arrNull.push(item.id)
                if (item.children) {
                  for (const jek of item.children) {
                    arrNull.push(jek.id)
                    this.dialogVisible = true
                  }
                } else {
                  this.dialogVisible = true
                  this.defaultCheckRole = []
                }
              }
            } else {
              this.dialogVisible = true
              this.defaultCheckRole = []
            }
          }
        } else {
          this.dialogVisible = true
          this.defaultCheckRole = []
        }
        this.$nextTick(() => {
          this.defaultCheckRole = arrNull
          this.$refs.adminTree.setCheckedKeys(this.defaultCheckRole)
        })
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // 确认保存
    setConfigUserRole () {
      this.$confirm('是否确认修改角色信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisable = false
        this.defaultRelev = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 保存修改详情按钮
    addConfigUserRole () {
      const newArr = []
      newArr.push(...this.setRoleIdArrFir, ...this.setRoleIdArrSen)
      const role = {
        menuList: newArr.length === 0 ? this.defaultCheckRole : newArr,
        remarks: this.roleDetailObj.userRemarkGet,
        roleId: this.roleDetailObj.userRoleIdGet,
        permission: this.roleDetailObj.permission,
        roleName: this.roleDetailObj.userNameGet
      }
      roleUpdate(role).then(res => {
        this.dialogVisible = false
        if (res.code === '200') {
          this.getRoleListFun()
          this.isDisable = true
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.setRoleIdArrFir = []
          this.setRoleIdArrSen = []
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
      // .catch(err => {
      //   this.$message({
      //     message: '服务器忙~',
      //     type: 'warning'
      //   })
      // })
    },
    roleNodeChange (checkedNodes, data) {
      this.setRoleIdArrFir = data.checkedKeys
      this.setRoleIdArrSen = data.halfCheckedKeys
      
    },
    // 关闭新增弹框
    closeAddPop(fromName){
      this.isShowaddRole = false
      // this.resetForm(fromName)
      this.$refs[fromName].resetFields();
    },
    // 重置 - 搜索 - 新增
    resetQuery(fromName) {
      // this.resetForm(fromName)
      
      this.$refs[fromName].resetFields();
      this.isShowaddRole = false
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getRoleListFun()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
  
.buttons {
  width: 100%;
  text-align: center;
}
</style>
